import {
  getChangeByPage,
  addChange,
  updateChange,
  delChange,
  getContractCodeAndName,
  getChangeType,
} from '@/services/platform/change';
import { getProductTypeList } from '@/services/templateMaintain/inspectionTemplate';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Tree, Select, Tooltip } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { Ellipsis } from '@/components/Ellipsis';
const Change: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [changeContractOptions, setChangeContractOptions] = useState([]);
  const [typeOptions, setTypeOptions] = useState([]);
  const [form] = Form.useForm();
  const ref = useRef(null);

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 40,
    },
    {
      title: '变更类型',
      dataIndex: 'changeType',
      width: 100,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const tempType = await getChangeType(null);
        const tempT: any[] = [];
        tempType.data.map((item: string) => {
          tempT.push({ value: item, lable: item });
        });
        return tempT;
      },
    },
    {
      title: '变更时间',
      dataIndex: 'changeTime',
      width: 100,
      align: 'center',
      sorter: true,

      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '合同名称',
    //   dataIndex: 'contractName',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      //title: '合同编号',
      title: '项目编号',
      dataIndex: 'contractCode',
      width: 120,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      width: 160,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '批次编号',
      dataIndex: 'batchPlanCode',
      width: 120,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '主计划编号',
    //   dataIndex: 'masterPlanCode',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },

    // {
    //   title: '变更原因',
    //   dataIndex: 'changeReason',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },

    // {
    //   title: '变更编号',
    //   dataIndex: 'changeCode',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    // {
    //   title: '柜体名称',
    //   dataIndex: 'productName',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '柜体类型',
      dataIndex: 'productType',
      width: 100,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproduct = await getProductTypeList(null);
        const productOptionContract: any[] = [];
        getproduct.data.map((item: any, index: any) => {
          productOptionContract.push({ value: item, label: item });
        });
        return productOptionContract;
      },
    },
    {
      title: '柜体编号',
      dataIndex: 'productCode',
      width: 120,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    // {
    //   title: '是否标准柜',
    //   dataIndex: 'isStandard',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text, record, _, action) => {
    //     return <div>{record.isStandard == 1 ? '是' : '否'}</div>;
    //   },
    // },
    // {
    //   title: '附件类型',
    //   dataIndex: 'category',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    // {
    //   title: '附件编号',
    //   dataIndex: 'fileCode',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    // {
    //   title: '附件版本号',
    //   dataIndex: 'version',
    //   width: 100,
    //  align: 'center',sorter: true,
    //   render: (text) => <>{Ellipsis(text)}</>,
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 80,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('变更详情');
            form.setFieldsValue({
              batchPlanCode: record.batchPlanCode,
              batchPlanId: record.batchPlanId,
              category: record.category,
              changeCode: record.changeCode,
              changeReason: record.changeReason,
              changeTime: record.changeTime,
              changeType: record.changeType,
              contractCode: record.contractCode,
              contractName: record.contractName,
              fileCode: record.fileCode,
              fileId: record.fileId,
              id: record.id,
              infoId: record.infoId,
              isStandard: record.isStandard,
              masterPlanCode: record.masterPlanCode,
              masterPlanId: record.masterPlanId,
              productCode: record.productCode,
              productId: record.productId,
              productName: record.productName,
              productType: record.productType,
              projectName: record.projectName,
              version: record.version,
            });
          }}
        >
          变更详情
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async (value) => {
          const result = await addChange(form.getFieldsValue());
          if (result != null) {
            message.success('添加成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch((err) => {
          setConfirmLoading(false);
        });
    } else {
      form
        .validateFields()
        .then(async () => {
          const result = await updateChange(form.getFieldsValue());
          if (result != null) {
            message.success('添加成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  //获取变更类型和变更名称
  const getChangeInfo = async () => {
    const res = await getContractCodeAndName(null);
    const changeOptionContract: any[] = [];
    res.data.map((item: any) => {
      changeOptionContract.push({ value: item.contractCode, label: item.contractName });
    });
    setChangeContractOptions(changeOptionContract);
    const tempType = await getChangeType(null);
    const tempT: any[] = [];
    tempType.data.map((item: string) => {
      tempT.push({ value: item, lable: item });
    });
    setTypeOptions(tempT);
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="变更记录查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        toolBarRender={(action, { selectedRows }) => [
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     setCreateOrUpdate(false);
          //     setFormTitle('新建');
          //     form.resetFields();
          //     setModalVisit(true);
          //   }}
          //   type="primary"
          // >
          //   新建
          // </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTran(ref.current.getFieldsValue());
          //     exportChange({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `Change.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          const result = await getChangeByPage({ ...params, sorters: sorters, filters: filters });
          getChangeInfo();
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1500, y: 350 }}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        // onOk={() => setModalVisit(false)}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        footer={[
          <Button key="back" onClick={() => setModalVisit(false)}>
            关闭
          </Button>,
        ]}
        width={650}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="变更类型"
            name="changeType"
            rules={[{ required: true, message: '请输入变更类型!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="变更时间"
            name="changeTime"
            rules={[{ required: true, message: '请输入变更时间!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="项目名称"
            name="contractName"
            rules={[{ required: true, message: '请输入合同名称!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="项目编号"
            name="contractCode"
            rules={[{ required: true, message: '请输入合同编号!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="柜体类型"
            name="productType"
            rules={[{ required: true, message: '请输入柜体类型！' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="柜体编号"
            name="productCode"
            rules={[{ required: true, message: '请输入柜体编号!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="批次编号"
            name="batchPlanCode"
            rules={[{ required: true, message: '请输入批次编号!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default Change;
